/*
NAME: 
DESCRIPTION: ;
PARAMETER:
    [
		{
			name : 'max_via_size',
			title : '最大via孔径',
			type : 'LineEdit',
			property : {tool_tip : '最大via孔径,默认是0.9mm'},
		},
		{
			name : 'step',
			title : '工作step',
			type : 'LineEdit',
			property : {tool_tip : '工作step,默认是net'},
		},
		{
			name : 'min_via_num',
			title : '最少via孔数',
			type : 'LineEdit',
			property : {tool_tip : '最少via孔数,默认是100'},
		},
		{
			name : 'equidistant_tolerance',
			title : '等间距公差',
			type : 'LineEdit',
			property : {tool_tip : '等间距公差,默认是0.005mm'},
		},
		{
            name : 'auto_save',
			title : '自动保存',
            type : 'RadioBox',
            property : {
				item_list:[
					{name:'yes',text:'YES'},
					{name:'no',text:'NO'},
				],
				tool_tip:'是否自动保存料号开关'
			}
        }
	]
	
 VERSION_HISTORY:
	V1.00 2020-04-20 Scott Sun
	    1.新版本
		
 HELP:
 	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		<p> 设置孔属性 </p>
		<br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<p> </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 无 </p>
		<br>
	</body></html>	
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
console.log("==============================>设置孔属性");
// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm; 
if (IKM==undefined ) { IKM = require('topcam.ikm6')($) }
var GEN = $.gen;
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db
var PAR = {}
if ($.par) {
	PAR = $.par
} else if ($.hasOwnProperty('script_parameter')){
	PAR = JSON.parse($.script_parameter);
}
if (mode === "aimdfm") {
	var database = require("topsin.database");
	database.addConnection($.conf.database_conf, "DFM");
	var QDfm = database.query("DFM");
	$.QDfm = QDfm;
	if ($.conf.product_type == "aimdfm") {
		QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				current_process_title: $.process_title
			},
			where: { id: $.task_id }
		});
	}
}
var Status = 'ok';
var resultData = [];

try {
	var par = PAR;
	var default_par = {
		step: 'net.+',
		step2:"net",
		max_via_size: "0.9mm",
		min_via_num: "100",
		equidistant_tolerance: "0.005mm",
		auto_save: "No"
	}
	for(var key in default_par){  // 设置默认属性
		if (!par.hasOwnProperty(key) || par[key] == ""){
			par[key] = default_par[key]
		}
	}
	var max_via_size = parseFloat(par.max_via_size) * 1000;
	var equidistant_tolerance = parseFloat(par.equidistant_tolerance);


	if(_.isEmpty(Job)){throw "参数Job不存在"}
	var job = Job.toLowerCase()
	if(!GEN.isJobExists({job:job})){throw "料号"+job+"不存在"}
	if(!GEN.isJobOpen({job:job})){ GEN.openJob({job:job}) }
    if(mode == "aimdfm"){
        if(GEN.checkInout({job:job,mode:"test"}) != 0){ throw "the job check" }
        GEN.checkInout({job:job,mode:"out"});
    }

	var verification;
	var jtg_via_comp_same = IKM.get_jobinfo({jobid:JobId, jobinfo:"jtg_via_comp_same"})  // via大小 = 器件孔 
	
	var jtg_via_size_final = IKM.get_jobinfo({jobid:JobId, jobinfo:"jtg_via_size_final"}) // 过孔孔径-成品

	if(/([<=]+)(.+)/ig.test(jtg_via_size_final)) {
		// console.log(RegExp.$1);
		// console.log(RegExp.$2);
		var tmp1 = RegExp.$1;
		var tmp2 = RegExp.$2;
		verification = function(size){
			if(tmp1 == "<"){
				return size < tmp2 *1000 && size/1000 != jtg_via_comp_same
			} else if(tmp1 == "≤") {
				return size <= tmp2 *1000 && size/1000 != jtg_via_comp_same
			}
		}
	} else {
		var tmp = jtg_via_size_final.split("/").map(function(v){return v * 1000})  // 0.3/0.5
		verification = function(size){
			var flag = false;
			tmp.forEach(function(v){
				if(Math.abs(v - size) < 1) {
					flag = true
				}
			})
			return flag
		}
	}
	// if(jtg_via_comp_same == "-"){
	// 	var jtg_via_size_final = IKM.get_jobinfo({jobid:JobId, jobinfo:"jtg_via_size_final"}) // 过孔孔径-成品
	// 	var tmp = jtg_via_size_final.split("/").map(function(v){return v * 1000})  // 0.3/0.5
	// 	verification = function(size){
	// 		return size <= tmp[1] && size >= tmp[0]
	// 	}
	// } else if(/^\d+$/ig.test(jtg_via_comp_same)) {
	// 	verification = function(size){
	// 		return size == jtg_via_comp_same * 1000
	// 	}
	// } else {
	// 	IKM.msg("via大小 = 器件孔 无法识别")
	// }
	
	// 通过matrix获取board属性的钻孔层
	var matrix = GEN.getMatrix({job:job})
	var dirll_layer = Object.keys(matrix).reduce(function(a,b){
		if(matrix[b].context == "board" && matrix[b].layer_type == "drill"){
			a.push(b)
		}
		return a
	},[])
	var stepList = GEN.getStepList({job:job})
	stepList = stepList.filter(function(step){
		var reg = new RegExp(par.step,"ig")
		return reg.test(step)
	})
	if (stepList.length == 0 && par.step2) {
		stepList = GEN.getStepList({job:job}).filter(function (v) {
			var tmpreg = new RegExp(par.step2, "ig");
			return tmpreg.test(v);
		})
	}
	if(stepList) {
		stepList.forEach(function(step){
			GEN.openStep({job:job,name:step})
			GEN.units({type:'mm'})
			GEN.affectedLayer({affected:'no',mode:'all'})
			GEN.selClearFeature()
			dirll_layer.forEach(function(layer){
				// 逐层设置钻孔工作层
				GEN.workLayer({name:layer,display_number:2,clear_before:'yes'})
				var sys = GEN.getLayerSymsHist({job:Job,step:'net',layer:'drl',units:'mm'})
				var includesys = [];
				// r700":{"symbol":"r700","line":"0","pad":"400","arc":"0","size":"700"},
				Object.keys(sys).forEach(function(key){
					var symbolinfo = sys[key];
					if(!symbolinfo.size && symbolinfo.width){
						symbolinfo.size = symbolinfo.width > symbolinfo.height ? symbolinfo.width : symbolinfo.height;
					}
					if(symbolinfo.size){
						symbolinfo.size = symbolinfo.size - 0;
						if(verification(symbolinfo.size)){
							includesys.push(symbolinfo.symbol)
						}
					}
				})
				if(includesys.length){
					GEN.selectByFilter({include_syms:includesys.join(";")})
					if(GEN.getSelectCount()>0){
						GEN.COM("cur_atr_set,attribute=.drill,option=via")
						GEN.COM("sel_change_atr,mode=add")
					}
				}

				GEN.selClearFeature()
				
				// 无环孔
				GEN.affectedLayer({affected:'no',mode:'all'})
				GEN.clearLayers()
				GEN.selClearFeature()
				GEN.affectedLayer({affected:'yes',layer:["gtl","gbl"]})
				GEN.selectByFilter({feat_types:'pad'})
				if(GEN.isLayerExists({job:job,layer:"s_outer_pad"})){GEN.deleteLayer({job:job, layer:["s_outer_pad"]})}
				if(GEN.getSelectCount()>0){
					GEN.selCopyOther({dest:'layer_name',target_layer:'s_outer_pad',invert:'no',dx:0,dy:0,size:0})
					GEN.affectedLayer({affected:'no',mode:'all'})
					GEN.workLayer({name:"s_outer_pad",display_number:2,clear_before:'yes'})
					GEN.selRefFeat({layers:layer,use:'filter',mode:'cover'})
					if(GEN.getSelectCount()>0){
						GEN.selMoveOther({target_layer:'s_outer_pad_1',invert:'no',dx:0,dy:0,size:0})
						GEN.workLayer({name:"s_outer_pad_1",display_number:2,clear_before:'yes'})
						GEN.selRefFeat({layers:"s_outer_pad",use:'filter',mode:'touch'})
						if(GEN.getSelectCount()>0){GEN.selDelete()}
						GEN.workLayer({name:layer,display_number:2,clear_before:'yes'})
						GEN.selRefFeat({layers:"s_outer_pad_1",use:'filter',mode:"include"})
						if(GEN.getSelectCount() > 0 ) {
							if(GEN.isLayerExists({job:job,layer:"whk"})){GEN.deleteLayer({job:job,step:step, layer:"whk"})}
							GEN.selCopyOther({dest:'layer_name',target_layer:'whk',invert:'no',dx:0,dy:0,size:0})
						}
						GEN.deleteLayer({job:job, layer:["s_outer_pad_1"]})
					}
					GEN.deleteLayer({job:job, layer:["s_outer_pad"]})
				}

				if(/^\d/.test(jtg_via_comp_same)) {
					IKM.msg("via = 器件孔为:" + jtg_via_comp_same)
				}
			})


			IKM.msg("请手动设置np孔和pth")
			GEN.PAUSE("pause")
			// GEN.closeStep()
		})
	} else {
		IKM.msg("没有找到step:"+par.step)
	}
	













	// 保存 
	if(/yes/ig.test(par.auto_save)){
		GEN.checkInout({job:job,mode:"out"})  // 结束保存料号 关闭料号
		GEN.saveJob({ job: job });
		GEN.checkInout({job:job,mode:"in"})
		GEN.closeJob({job:job})
	} else {
		GEN.checkInout({job:job,mode:"in"})
	}


    if (mode === "aimdfm") {
		$.QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				progress: 33.33
			},
			where: { id: $.task_id }
		});
		if (GEN.hasError()) {
			Status = 'error';
			resultData.push({ type: "error", title: "GEN错误!", detail: [{ desc: _.join(GEN.STATUS, "\n") }] });
			return {
				status: Status,
				result_data: resultData
			};
		} else {
			resultData.push({ type: "info", title: "操作完成, 请注意检查!" });
			return {
				status: Status,
				result_data: resultData
			};
		}
	}else {
		return "Done"
	}
} catch (e) {
	IKM.msg(_.join(GEN.STATUS, "\n"))
	IKM.msg(e)
    Status = 'error';
    resultData.push({type: "error", title: "脚本执行出错!", detail: [{desc: _.toString(e)}]});
	return (mode === "aimdfm") ? {status: Status, result_data: resultData} : "Error";
}